#ifndef AI_WATER_ANALYZER_H
#define AI_WATER_ANALYZER_H

#include <Arduino.h>

// 水质数据结构
typedef struct {
  float phValue;         // pH值
  float doValue;         // 溶解氧 (mg/L)
  float ecValue;         // 电导率 (μS/cm)
  float temperature;     // 温度 (°C)
  float turbidity;       // 浊度 (NTU)
  unsigned long timestamp; // 时间戳
} WaterQualityData;

// 异常类型定义
enum AnomalyType {
  NO_ANOMALY = 0,
  PH_ABNORMAL = 1,
  DO_ABNORMAL = 2,
  EC_ABNORMAL = 3,
  TEMP_ABNORMAL = 4,
  TURBIDITY_ABNORMAL = 5,
  MULTIPLE_ANOMALIES = 6
};

// 水质参数阈值定义
struct WaterQualityThresholds {
  float minPh;           // 最小pH值
  float maxPh;           // 最大pH值
  float minDo;           // 最小溶解氧
  float maxDo;           // 最大溶解氧
  float minEc;           // 最小电导率
  float maxEc;           // 最大电导率
  float minTemp;         // 最小温度
  float maxTemp;         // 最大温度
  float minTurbidity;    // 最小浊度
  float maxTurbidity;    // 最大浊度
};

class AIWaterAnalyzer {
private:
  // 水质参数阈值
  WaterQualityThresholds thresholds;
  
  // 历史数据缓冲区，用于移动平均滤波和趋势分析
  static const int HISTORY_BUFFER_SIZE = 30; // 30个数据点 (5分钟的数据)
  float phHistory[HISTORY_BUFFER_SIZE];
  float doHistory[HISTORY_BUFFER_SIZE];
  float ecHistory[HISTORY_BUFFER_SIZE];
  float tempHistory[HISTORY_BUFFER_SIZE];
  float turbidityHistory[HISTORY_BUFFER_SIZE];
  
  // 缓冲区索引
  int bufferIndex;
  
  // 计算移动平均值
  float calculateMovingAverage(float* buffer, int size);
  
  // 计算数据变化率
  float calculateRateOfChange(float* buffer, int size);
  
  // Z-score异常检测
  bool detectZScoreAnomaly(float value, float* history, int size, float threshold);
  
  // 趋势分析
  bool detectTrendAnomaly(float* history, int size, float threshold);

public:
  // 构造函数
  AIWaterAnalyzer();
  
  // 初始化AI分析器
  void init();
  
  // 设置水质参数阈值
  void setThresholds(WaterQualityThresholds newThresholds);
  
  // 检测水质异常
  int detectAnomaly(WaterQualityData data);
  
  // 获取异常类型描述
  String getAnomalyDescription(int anomalyType);
  
  // 预测未来水质趋势 (简化版)
  float predictFutureValue(float* history, int size, int steps);
}; // 类定义结束

// 构造函数
AIWaterAnalyzer::AIWaterAnalyzer() {
  // 设置默认阈值（适合大多数淡水环境监测）
  thresholds.minPh = 6.5;
  thresholds.maxPh = 8.5;
  thresholds.minDo = 5.0;
  thresholds.maxDo = 12.0;
  thresholds.minEc = 100.0;
  thresholds.maxEc = 1500.0;
  thresholds.minTemp = 0.0;
  thresholds.maxTemp = 35.0;
  thresholds.minTurbidity = 0.0;
  thresholds.maxTurbidity = 50.0;
  
  // 初始化历史数据缓冲区
  for (int i = 0; i < HISTORY_BUFFER_SIZE; i++) {
    phHistory[i] = 7.0; // 中性pH值
    doHistory[i] = 8.0; // 标准溶解氧
    ecHistory[i] = 500.0; // 中等电导率
    tempHistory[i] = 25.0; // 室温
    turbidityHistory[i] = 5.0; // 低浊度
  }
  
  bufferIndex = 0;
}

// 初始化AI分析器
void AIWaterAnalyzer::init() {
  // 初始化完成
  Serial.println("AI水质分析器已初始化");
}

// 设置水质参数阈值
void AIWaterAnalyzer::setThresholds(WaterQualityThresholds newThresholds) {
  thresholds = newThresholds;
}

// 计算移动平均值
float AIWaterAnalyzer::calculateMovingAverage(float* buffer, int size) {
  float sum = 0.0;
  for (int i = 0; i < size; i++) {
    sum += buffer[i];
  }
  return sum / size;
}

// 计算数据变化率
float AIWaterAnalyzer::calculateRateOfChange(float* buffer, int size) {
  if (size < 2) return 0.0;
  
  // 计算最近10个数据点的变化率
  int recentPoints = min(10, size);
  float firstValue = buffer[(bufferIndex - recentPoints + 1 + size) % size];
  float lastValue = buffer[bufferIndex];
  
  return (lastValue - firstValue) / recentPoints;
}

// Z-score异常检测
bool AIWaterAnalyzer::detectZScoreAnomaly(float value, float* history, int size, float threshold) {
  // 计算平均值
  float mean = calculateMovingAverage(history, size);
  
  // 计算标准差
  float sumSquaredDifferences = 0.0;
  for (int i = 0; i < size; i++) {
    sumSquaredDifferences += pow(history[i] - mean, 2);
  }
  float stdDev = sqrt(sumSquaredDifferences / size);
  
  // 防止除零错误
  if (stdDev == 0) return false;
  
  // 计算Z-score
  float zScore = abs(value - mean) / stdDev;
  
  // 如果Z-score超过阈值，则视为异常
  return zScore > threshold;
}

// 趋势分析
bool AIWaterAnalyzer::detectTrendAnomaly(float* history, int size, float threshold) {
  float rateOfChange = calculateRateOfChange(history, size);
  return abs(rateOfChange) > threshold;
}

// 检测水质异常
int AIWaterAnalyzer::detectAnomaly(WaterQualityData data) {
  // 更新历史数据缓冲区
  phHistory[bufferIndex] = data.phValue;
  doHistory[bufferIndex] = data.doValue;
  ecHistory[bufferIndex] = data.ecValue;
  tempHistory[bufferIndex] = data.temperature;
  turbidityHistory[bufferIndex] = data.turbidity;
  
  // 更新缓冲区索引
  bufferIndex = (bufferIndex + 1) % HISTORY_BUFFER_SIZE;
  
  // 检测各参数异常
  bool phAnomaly = (data.phValue < thresholds.minPh || data.phValue > thresholds.maxPh) ||
                   detectZScoreAnomaly(data.phValue, phHistory, HISTORY_BUFFER_SIZE, 2.5) ||
                   detectTrendAnomaly(phHistory, HISTORY_BUFFER_SIZE, 0.1);
  
  bool doAnomaly = (data.doValue < thresholds.minDo || data.doValue > thresholds.maxDo) ||
                   detectZScoreAnomaly(data.doValue, doHistory, HISTORY_BUFFER_SIZE, 2.5) ||
                   detectTrendAnomaly(doHistory, HISTORY_BUFFER_SIZE, 0.3);
  
  bool ecAnomaly = (data.ecValue < thresholds.minEc || data.ecValue > thresholds.maxEc) ||
                   detectZScoreAnomaly(data.ecValue, ecHistory, HISTORY_BUFFER_SIZE, 2.5) ||
                   detectTrendAnomaly(ecHistory, HISTORY_BUFFER_SIZE, 50.0);
  
  bool tempAnomaly = (data.temperature < thresholds.minTemp || data.temperature > thresholds.maxTemp) ||
                     detectZScoreAnomaly(data.temperature, tempHistory, HISTORY_BUFFER_SIZE, 2.5) ||
                     detectTrendAnomaly(tempHistory, HISTORY_BUFFER_SIZE, 0.5);
  
  bool turbidityAnomaly = (data.turbidity < thresholds.minTurbidity || data.turbidity > thresholds.maxTurbidity) ||
                          detectZScoreAnomaly(data.turbidity, turbidityHistory, HISTORY_BUFFER_SIZE, 2.5) ||
                          detectTrendAnomaly(turbidityHistory, HISTORY_BUFFER_SIZE, 2.0);
  
  // 统计异常数量
  int anomalyCount = 0;
  int anomalyType = NO_ANOMALY;
  
  if (phAnomaly) { anomalyCount++; anomalyType = PH_ABNORMAL; }
  if (doAnomaly) { anomalyCount++; anomalyType = DO_ABNORMAL; }
  if (ecAnomaly) { anomalyCount++; anomalyType = EC_ABNORMAL; }
  if (tempAnomaly) { anomalyCount++; anomalyType = TEMP_ABNORMAL; }
  if (turbidityAnomaly) { anomalyCount++; anomalyType = TURBIDITY_ABNORMAL; }
  
  // 如果有多个异常，返回MULTIPLE_ANOMALIES
  if (anomalyCount > 1) {
    anomalyType = MULTIPLE_ANOMALIES;
  }
  
  return anomalyType;
}

// 获取异常类型描述
String AIWaterAnalyzer::getAnomalyDescription(int anomalyType) {
  switch (anomalyType) {
    case PH_ABNORMAL:
      return "pH值异常";
    case DO_ABNORMAL:
      return "溶解氧异常";
    case EC_ABNORMAL:
      return "电导率异常";
    case TEMP_ABNORMAL:
      return "温度异常";
    case TURBIDITY_ABNORMAL:
      return "浊度异常";
    case MULTIPLE_ANOMALIES:
      return "多个参数异常";
    default:
      return "水质正常";
  }
}

// 预测未来水质趋势 (简化版)
float AIWaterAnalyzer::predictFutureValue(float* history, int size, int steps) {
  // 简化的线性预测模型
  float recentRate = calculateRateOfChange(history, size);
  float lastValue = history[bufferIndex];
  
  return lastValue + (recentRate * steps);
}

#endif // AI_WATER_ANALYZER_H